#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use English qw( -no_match_vars );
use autodie;

use Test::More;

use File::Temp qw( tempdir );
my $TEMPDIR = tempdir( CLEANUP => 1 );
use File::Path qw( make_path );
make_path($TEMPDIR);

ok(system('perl', "@abs_top_builddir@/t/mock-slapcat", "--tempdir=$TEMPDIR", '--reset-count') == 0, 'resetting mock counter');
my $counter   = slurp_from_cmd("perl @abs_top_builddir@/t/mock-slapcat --tempdir=$TEMPDIR --show-count");
chomp($counter);
is($counter, 0, 'counter should be zero initially');

my $reference = slurp_from_cmd("cat @abs_top_srcdir@/t/testdata/data0.ldif");
my $data      = slurp_from_cmd("perl @abs_top_builddir@/t/mock-slapcat --tempdir=$TEMPDIR");
$counter      = slurp_from_cmd("perl @abs_top_builddir@/t/mock-slapcat --tempdir=$TEMPDIR --show-count");
chomp($counter);

is($data, $reference, 'LDIF data from first run');
is($counter, 1, 'counter should be one');

$reference = slurp_from_cmd("cat @abs_top_srcdir@/t/testdata/data1.ldif");
$data      = slurp_from_cmd("perl @abs_top_builddir@/t/mock-slapcat --tempdir=$TEMPDIR");
$counter   = slurp_from_cmd("perl @abs_top_builddir@/t/mock-slapcat --tempdir=$TEMPDIR --show-count");
chomp($counter);

is($data, $reference, 'LDIF data from second run');
is($counter, 2, 'counter should be two at the end');

done_testing();

sub slurp_from_cmd {
    my ($cmd) = @_;

    open(my $fh, '-|', $cmd);
    my $data = do { local $RS; <$fh> };
    close($fh);

    return $data;
}
